package com.example.common.mvvm.repository;

import com.blankj.utilcode.util.NetworkUtils;
import com.example.common.entity.ErrorEntity;
import com.example.network_skd.BaseEntity;
import com.example.network_skd.RxFunc;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class BaseRepository {
    protected Observable<BaseEntity> observableFunc(Observable observable){
        return observable.map(new RxFunc());

    }

    protected RequestBody createBody(Map<String, Object> map){
        Gson gson = new Gson();
        String s = gson.toJson(map);
        return RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),s);
    }
    protected Observable mergerObservable(Observable ... observables){
        List<Observable<BaseEntity>> list = new ArrayList<>();
        for (int i = 0; i < observables.length; i++) {
            list.add(observableFunc(observables[i]));
        }
        return Observable.merge(list);
    }

    protected Observable<BaseEntity> checkNetWork(Observable observable){
        if (NetworkUtils.isConnected()){
            return observableFunc(observable);
        }else {
            ErrorEntity errorEntity = new ErrorEntity();
            errorEntity.message="网络错误";
            errorEntity.status = 200;
            return observableFunc(Observable.just(errorEntity));
        }
    }
}
